<template>
  <PageWrapper title="角色列表" contentFullHeight contentClass="flex">
    <!-- <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" /> -->
    <div class="flex-1">
      <a-row gutter="16">
        <a-col span="10">
          <BasicTable @register="registerTable">
            <template #toolbar>
              <a-button type="default" v-auth="['10022', RoleEnum.SUPER]" @click="handleCreate"
                >添加</a-button
              >
              <a-button
                type="primary"
                v-auth="['10023', RoleEnum.SUPER]"
                v-if="!isEdit"
                @click="triggerRelation"
                >关联设置</a-button
              >
              <a-button type="default" v-if="isEdit" @click="isEdit = false">取消</a-button>
              <a-button type="primary" v-if="isEdit" @click="save">保存</a-button>
            </template>
            <template #name="{ record }">
              <a @click="titleClick($event, record)">{{ record.name }}</a>
            </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    onClick: handleEdit.bind(null, record),
                    label: '',
                    auth: ['10024', RoleEnum.SUPER],
                  },
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    label: '',
                    auth: ['10025', RoleEnum.SUPER],
                    popConfirm: {
                      title: '确认删除该角色吗?',
                      confirm: handleDelete.bind(null, record),
                    },
                  },
                ]"
              />
            </template>
          </BasicTable>
        </a-col>
        <a-col span="7">
          <div class="com-bg">
            <div style="height: 40px; padding-top: 8px" class="pl-2 flex items-center">
              <h3>关联相机分组</h3>
            </div>
            <div> <BasicTable @register="registerTable1" /></div>
          </div>
        </a-col>
        <a-col span="7" class="com-bg">
          <div class="com-bg">
            <div style="height: 40px; padding-top: 8px" class="pl-2 flex items-center">
              <h3>关联相机</h3>
            </div>
            <div> <BasicTable @register="registerTable2" /></div>
          </div>
        </a-col>
      </a-row>
    </div>

    <RoleModal @register="registerModal" @success="handleSuccess" />
    <RoleConfigModal @register="registerModal2" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, watch } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    bindRoleCameras,
    deleteRole,
    getDeviceAll,
    getGroupList,
    getRoleBindCameras,
    getRoleList,
  } from '/@/api/sys/user';
  import { PageWrapper } from '/@/components/Page';
  // import DeptTree from './DeptTree.vue';

  import { useModal } from '/@/components/Modal';

  import { columns } from './role.data';
  import RoleModal from './RoleModal.vue';
  import RoleConfigModal from './RoleConfigModal.vue';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import { Col, Row } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { RoleEnum } from '/@/enums/roleEnum';

  export default defineComponent({
    name: 'Role',
    components: {
      BasicTable,
      PageWrapper,
      TableAction,
      RoleModal,
      RoleConfigModal,
      'a-row': Row,
      'a-col': Col,
    },
    setup() {
      const [registerModal, { openModal }] = useModal();
      const [registerModal2, { openModal: op2 }] = useModal();
      const userStore = useUserStoreWithOut();
      const [registerTable, { reload, setSelectedRowKeys }] = useTable({
        // title: '账号列表',
        api: getRoleList,
        columns,
        searchInfo: {
          pid: userStore.getUserInfo.id,
        },
        clickToRowSelect: true,
        indexColumnProps: {
          width: 80,
        },
        rowSelection: {
          type: 'radio',
          onChange: updateRelation,
        },
        rowKey: 'id',
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        afterFetch: (res) => {
          setTimeout(() => {
            if (res && res[0]) {
              setSelectedRowKeys([res[0].id]);
            }
          }, 100);
          return res;
        },
        actionColumn: {
          width: 90,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      const [
        registerTable1,
        {
          reload: reload1,
          getSelectRowKeys: getSelectRowKeys1,
          setSelectedRowKeys: setSelectedRowKeys1,
        },
      ] = useTable({
        // title: '账号列表',
        api: getGroupList,
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            // width: 120,
          },
        ],
        clickToRowSelect: false,
        indexColumnProps: {
          width: 80,
        },
        rowSelection: {
          type: 'checkbox',
          getCheckboxProps: () => ({
            disabled: !isEdit.value,
          }),
        },
        rowKey: 'id',
        useSearchForm: false,
        pagination: false,
        showTableSetting: false,
        bordered: true,
      });
      const [
        registerTable2,
        {
          reload: reload2,
          getSelectRowKeys: getSelectRowKeys2,
          setSelectedRowKeys: setSelectedRowKeys2,
        },
      ] = useTable({
        // title: '账号列表',
        api: getDeviceAll,
        clickToRowSelect: false,
        columns: [
          {
            title: 'SIM卡号码',
            dataIndex: 'sim_number',
            // width: 120,
          },
        ],
        indexColumnProps: {
          width: 80,
        },
        rowSelection: {
          type: 'checkbox',
          getCheckboxProps: () => ({
            disabled: !isEdit.value,
          }),
        },
        rowKey: 'sim_number',
        useSearchForm: false,
        pagination: false,
        showTableSetting: false,
        bordered: true,
      });

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleDelete(record: Recordable) {
        deleteRole(record.id).then(
          () => {
            // msg
            handleSuccess();
          },
          () => {},
        );
      }

      function handleSuccess() {
        reload();
      }

      // 点击图像相机编号事件，与行点击事件区分开，
      function titleClick(e: PointerEvent, item) {
        e.stopPropagation();
        op2(true, {
          data: item,
        });
        // 弹框展示当前图像信息
      }

      let roleId = 0;

      async function updateRelation(rows) {
        let gs: any[] = [],
          cs: any[] = [];
        if (rows.length) {
          roleId = rows[0];
          const res = await getRoleBindCameras(roleId);
          if (res) {
            res.forEach((v) => {
              if (v.type === 2) {
                gs.push(parseInt(v.number));
              } else {
                cs.push(v.number);
              }
            });
          }
        }

        setSelectedRowKeys1(gs);
        setSelectedRowKeys2(cs);
        // getRoleBindCameras(roleId).then((res) => {});
      }

      const isEdit = ref<boolean>(false);

      watch(isEdit, () => {
        reload1();
        reload2();
      });

      function triggerRelation() {
        isEdit.value = true;
        // setProps2({
        //   rowSelection: {
        //     type: 'checkbox',
        //     getCheckboxProps: () => ({
        //       disabled: false,
        //     }),
        //   },
        // });
      }
      const { createMessage } = useMessage();

      function save() {
        bindRoleCameras({
          role_id: roleId,
          asset_nums: [
            ...getSelectRowKeys2().map((v) => ({
              type: 1,
              number: v,
            })),
            ...getSelectRowKeys1().map((v) => ({
              type: 2,
              number: v.toString(),
            })),
          ],
        }).then(() => {
          createMessage.success('配置成功！');
          isEdit.value = false;
        });
      }

      return {
        registerModal2,

        titleClick,
        registerTable,
        registerTable1,
        registerTable2,
        registerModal,

        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        triggerRelation,
        isEdit,
        save,
        RoleEnum
      };
    },
  });
</script>
